package com.pb.camera.adapter;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.pb.camera.R;
import com.pb.camera.application.App;
import com.pb.camera.bean.Camera;
import com.pb.camera.bean.DeviceMode;
import com.pb.camera.bean.Equipment;
import com.pb.camera.bean.Room;
import com.pb.camera.utils.JsonAnalyle;
import com.pb.camera.utils.JsonUtil;
import com.pb.camera.utils.Url;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CameraPictureListViewAdapter extends BaseAdapter implements OnClickListener {
    private List<Equipment> equipments;
    private Activity ac;
    private BitmapUtils bitmapUtils;
    //	    private  boolean   updataBitmap;
    private Dialog dialog;
    private Dialog replaceNameDialog;
    private Dialog deleteDeviceDialog;
    private Dialog inviteFriendDialog;
    private int clickPosition;
    private ViewHolder currentHolder;
    /**
     * dialog 内部显示的旋转动画
     */
    private AnimationDrawable an;
    private Dialog progressDialog;

    /**
     * 新建的房间或重命名的房间
     * 重命名的设备的名字
     */
    private String newHomeName;
    private Dialog nameDialog;

    private HttpUtils httpUtils;

    public CameraPictureListViewAdapter(List<Equipment> equipments, Activity a) {
        super();
        this.equipments = equipments;
        this.ac = ac;
        bitmapUtils = App.getInstance().bitmapUtils;
        this.httpUtils = new HttpUtils();
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        if (equipments != null) {
            return equipments.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder holder;
        if (convertView == null) {
            convertView = ac.getLayoutInflater().inflate(R.layout.camera_listview_adapter, parent, false);
            holder = new ViewHolder();
            holder.position = position;
            holder.cameraPicture = (ImageView) convertView.findViewById(R.id.camera_listview_image);
            holder.image_more = (ImageView) convertView.findViewById(R.id.camera_listview_image_more);
            holder.text_camera_name = (TextView) convertView.findViewById(R.id.camera_listview_camera_name);
            holder.text_online = (TextView) convertView.findViewById(R.id.camera_listview_text_online);
            holder.image_dector = (ImageView) convertView.findViewById(R.id.camera_listview_image_dector);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final ViewHolder temHoler = holder;
        convertView.setTag(holder);
        holder.position = position;
        holder.image_more.setTag(holder);
        holder.image_more.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                //弹出管理camera的对话框
                currentHolder = temHoler;
                showCameraDialog();
            }
        });
        holder.cameraPicture.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });
        return convertView;
    }

    private class ViewHolder {
        int position;
        public ImageView cameraPicture;
        public ImageView image_more;
        public TextView text_camera_name;
        public ImageView image_dector;
        public TextView text_online;
    }

    public void resetEquipmentList(List<Equipment> equipments) {
        this.equipments = equipments;
    }

    /**
     * 重网络上请求图片
     * 目前看来是没有什么作用的
     * 图片需要是在查看摄像头的详情的时候生成的
     *
     * @param url
     * @param view
     */
    private void getBitmapFromNet(String url, ImageView view) {
        bitmapUtils.display(view, url);
        Bitmap b = null;
    }

    /**
     * 清除sd卡里面的缓存
     * 当重详情页面回转过来的时候
     *
     * @param name
     */
    private void clearBitmapDiskChache(String name) {


    }

    /**
     * 把图片保存到sd卡里面去
     */
    public void saveFile(Bitmap bm, String fileName) throws IOException {
        File dirFile = new File(App.getInstance().bitmapLocalPath);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(App.getInstance().bitmapLocalPath + "/" + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }


    /**
     * 从sd卡里面获取bitmap
     */
    private void getBitmapFromDisk(String name, ImageView view) {
        Bitmap bitmap = null;
        bitmap = BitmapFactory.decodeFile(App.getInstance().bitmapLocalPath + "/" + name);

        //bitmapUtils.getBitmapFileFromDiskCache(name);
        if (bitmap == null) {
            view.setImageResource(R.drawable.default_camera_picture);
        } else {
            view.setImageBitmap(bitmap);
        }
    }


    private void createCameraDialog() {
        dialog = new Dialog(ac, R.style.dialog);
        dialog.show();
        dialog.setContentView(R.layout.gf_camera_more_dialog);
        View view = dialog.getWindow().getDecorView();
        ImageView imageDector = (ImageView) view.findViewById(R.id.camera_manager_move_dector);
        imageDector.setOnClickListener(this);
        ImageView imageNet = (ImageView) view.findViewById(R.id.camera_manager_net_set);
        imageNet.setOnClickListener(this);
        ImageView imageShare = (ImageView) view.findViewById(R.id.camera_manager_share);
        imageShare.setOnClickListener(this);
        ImageView imageRename = (ImageView) view.findViewById(R.id.camera_manager_rename);
        imageRename.setOnClickListener(this);
        ImageView imageDelete = (ImageView) view.findViewById(R.id.camera_manager_delete);
        imageDelete.setOnClickListener(this);
        ImageView imageMore = (ImageView) view.findViewById(R.id.camera_manager_more);
        imageMore.setOnClickListener(this);
    }


    private void createReplaceDeviceDialog() {
        replaceNameDialog = new Dialog(ac, R.style.dialog);
        replaceNameDialog.show();
        replaceNameDialog.setContentView(R.layout.dialog_replace_room_name);
        TextView tv_delete = (TextView) replaceNameDialog.getWindow().getDecorView().findViewById(R.id.tv_delete);
        tv_delete.setText("重命名房间");
        final EditText ed = (EditText) replaceNameDialog.getWindow().getDecorView().findViewById(R.id.et_roomname);
        TextView cancle = (TextView) replaceNameDialog.getWindow().getDecorView().findViewById(R.id.bt_cancel);
        cancle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });
        TextView certain = (TextView) replaceNameDialog.getWindow().getDecorView().findViewById(R.id.bt_submit);
        certain.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String name = ed.getText().toString();
                if (name == null || name.equals("")) {
                    Toast.makeText(ac, "房间名不可以是空", Toast.LENGTH_SHORT).show();
                } else {
                    int userId = Integer.parseInt(App.getInstance().getUserId());
                    String url = Url.replaceEquipmentOtherName(userId, equipments.get(currentHolder.position).getDids(), name);
                    netWorkOperateDevice(url, 1, currentHolder.position, name);
                }
            }
        });
    }

    /**
     * 修改房间的名字
     */
    private void showReplaceDeviceDiaolog() {
        if (replaceNameDialog == null) {
            createReplaceDeviceDialog();
        } else {
            if (!replaceNameDialog.isShowing()) {
                replaceNameDialog.show();
            }
        }

    }

    private void createDeleteDeviceDialog() {
        deleteDeviceDialog = new Dialog(ac, R.style.dialog);

        deleteDeviceDialog.show();
        deleteDeviceDialog.setContentView(R.layout.dialog_delete_room);
        TextView cancle = (TextView) deleteDeviceDialog.getWindow().getDecorView().findViewById(R.id.bt_cancel);
        TextView certain = (TextView) deleteDeviceDialog.getWindow().getDecorView().findViewById(R.id.bt_submit);
        cancle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                deleteDeviceDialog.dismiss();
            }
        });
        certain.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String url = Url.removeEquipment(App.getInstance().getUserId(), equipments.get(currentHolder.position).getGroup(), equipments.get(currentHolder.position).getDids());
                netWorkOperateDevice(url, 0, currentHolder.position, null);
            }
        });
    }

    /**
     * 确认删除房间的对话框
     */
    private void showDeleteDeviceDialog() {
        if (deleteDeviceDialog == null) {
            createDeleteDeviceDialog();
        } else {
            if (!deleteDeviceDialog.isShowing()) {
                deleteDeviceDialog.show();
            }
        }
    }

    private void createInviteFriendDialog() {
        inviteFriendDialog = new Dialog(ac, R.style.dialog);
        inviteFriendDialog.show();
        inviteFriendDialog.setContentView(R.layout.dialog_invite_people);
        View view = inviteFriendDialog.getWindow().getDecorView();
        final EditText edit = (EditText) view.findViewById(R.id.et_invite_person);
        TextView cancle = (TextView) view.findViewById(R.id.bt_cancel);
        TextView certain = (TextView) view.findViewById(R.id.bt_submit);
        cancle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                inviteFriendDialog.dismiss();
            }
        });
        certain.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String name = edit.getText().toString();
                if (name == null || name.equals("")) {
                    Toast.makeText(ac, "用户名不可以为空", Toast.LENGTH_SHORT).show();
                } else {

                }
            }
        });

    }

    /**
     * 邀请自己的好友的对话框
     */
    private void showInviteFriendDialog() {
        if (inviteFriendDialog == null) {
            createInviteFriendDialog();
        } else {
            if (!inviteFriendDialog.isShowing()) {
                inviteFriendDialog.show();
            }
        }
    }

    private void intviteFriend(String name) {
        String invitePersonUrl = Url.invitePerson(name, equipments.get(currentHolder.position).getGroup());
        httpUtils.send(HttpMethod.POST, invitePersonUrl, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0,
                                  String arg1) {
                // TODO Auto-generated method stub
                Toast.makeText(ac, "网络连接失败,请稍后重试", 0).show();
            }

            @Override
            public void onSuccess(
                    ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                if (TextUtils.isEmpty(arg0.result)) {
                    ac.runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(ac, "服务器出错,请稍后重试", 0).show();
                        }
                    });
                } else {
                    HashMap<String, Object> invitePersonMap = JsonUtil.parseJsonToMap(arg0.result);
                    int inviteCode = Integer.parseInt(invitePersonMap.get("errcode").toString());
                    switch (inviteCode) {
                        case 0:
                            ac.runOnUiThread(new Runnable() {
                                public void run() {
                                    Toast.makeText(ac, "邀请成功", 0).show();
                                }
                            });
                            break;
                        case 50011:
                            ac.runOnUiThread(new Runnable() {
                                public void run() {
                                    Toast.makeText(ac, "用户不存在", 0).show();
                                }
                            });
                            break;
                        case 50013:
                            ac.runOnUiThread(new Runnable() {
                                public void run() {
                                    Toast.makeText(ac, "用户已邀请", 0).show();
                                }
                            });
                            break;
                        case 50014:
                            ac.runOnUiThread(new Runnable() {
                                public void run() {
                                    Toast.makeText(ac, "不能邀请自己", 0).show();
                                }
                            });
                            break;
                        case -1:
                            ac.runOnUiThread(new Runnable() {
                                public void run() {
                                    Toast.makeText(ac, "系统繁忙", 0).show();
                                }
                            });
                            break;
                    }
                }
            }
        });

    }

    /**
     * 修改设备的名字
     */
    private void nameOperate(String name) {
        int id = Integer.parseInt(App.getInstance().getUserId());
        String url = Url.replaceEquipmentOtherName(id, equipments.get(currentHolder.position).getDids(), name);
        netWorkOperateDevice(url, 1, currentHolder.position, name);
    }

    /**
     * 弹出对话框
     *
     * @param position
     * @param listItem+
     */
    private void showCameraDialog() {
        if (dialog == null) {
            createCameraDialog();
        } else {
            if (!dialog.isShowing()) {
                dialog.show();
            }
        }

    }

    /**
     * 网络访问的时候弹出的旋转对话框
     * 例如更改名字或是删除设备的时候
     */
    private void createProgressDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ac,
                R.style.dialog);
        progressDialog = builder.create();
        View dialogContentView = ac.getLayoutInflater().inflate(
                R.layout.rotate_image_view, null);
        ImageView imageView = (ImageView) dialogContentView
                .findViewById(R.id.dialog_rotate_drawable);
        an = (AnimationDrawable) imageView.getDrawable();

    }

    private void showProgressDialog() {
        if (!progressDialog.isShowing()) {
            progressDialog.show();
            an.start();
        }

//		WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
//		lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
//		lp.gravity = Gravity.CENTER;
//		dialog.getWindow().setAttributes(lp);
//		dialog.setContentView(dialogContentView);

    }

    private void dismisssProgressDialog() {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
            an.stop();
        }

    }

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        switch (view.getId()) {
            case R.id.camera_manager_delete:
                onDialogDeleteClick(currentHolder.position);
                break;
            case R.id.camera_manager_more:
                onDialogMoreClick(currentHolder.position);
                break;
            case R.id.camera_manager_move_dector:
                view.setSelected(!view.isSelected());

                break;
            case R.id.camera_manager_net_set:
                onDialogNetSetClick(currentHolder.position);
                break;

            case R.id.camera_manager_rename:

                onDialogRenameClick(currentHolder.position);
                break;

            case R.id.camera_manager_share:
                onDialogShareClick(currentHolder.position);
                break;

            default:
                break;
        }

    }

    //指令为0
    private void onDialogDeleteClick(int position) {
        showDeleteDeviceDialog();

    }

    //指令为1
    private void onDialogRenameClick(int position) {
        showReplaceDeviceDiaolog();
//		showRenameDialog();
//		   int userId=Integer.parseInt(App.getInstance().getUserId());
//	       String url=Url.replaceEquipmentOtherName(userId,equipments.get(position).getDids(), newName);
//	       netWorkOperateDevice(url, 1,position);	  
    }

    /**
     * 网络配置接口
     *
     * @param position
     */
    private void onDialogNetSetClick(int position) {
        Equipment e = equipments.get(position);


    }

    private void onDialogShareClick(int position) {
        showInviteFriendDialog();

    }

    private void onDialogMoreClick(int position) {
        Equipment e = equipments.get(position);
        Intent in = new Intent();
        //跳转到跟多的界面里面

    }


    /**
     * @param url
     * @param order    网络指令  0是删除,1是重命名
     * @param position 操作的是哪个设备
     * @param name     重命名设备的时候,设备的新名字
     */
    private void netWorkOperateDevice(String url, final int order, final int position, final String name) {
        showProgressDialog();
        httpUtils.send(HttpMethod.POST, url, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                Toast.makeText(ac, "网络访问失败,请检查你的网络", Toast.LENGTH_SHORT).show();
                dismisssProgressDialog();
            }

            @Override
            public void onSuccess(final ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                ac.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        boolean flag = JsonAnalyle.jsonAnalyse(arg0.result, ac, null, null);
                        if (flag) {
                            handleDeviceOperateOutcome(position, order, name);
                        }
                        dismisssProgressDialog();
                    }
                });
            }
        });

    }

    /**
     * 处理访问网络修改设备的名字,删除设备的的结果
     *
     * @param order 网络指令  0是删除,1是重命名
     */
    private void handleDeviceOperateOutcome(int position, int order, String name) {
        if (order == 0) {
            equipments.remove(position);
            notifyDataSetChanged();
        } else if (order == 1) {
            equipments.get(position).setDalias(name);
            notifyDataSetChanged();
        }

    }

    /**
     * 把自己的设备分享给自己的好友
     */
    private void netWorkOperateShareDevice(String url) {


    }


}
